package org.grow.ceto.controller;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.grow.ceto.dao.PlayerDao;
import org.grow.ceto.entity.*;
import org.grow.ceto.exception.CetoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author: xwg
 * @CreateDate: 21-8-25
 */

@RestController
@RequestMapping("/ceto/player")
public class PlayerController {

    @Autowired
    private PlayerDao playerDao;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @GetMapping("/showSome")
    public List<Player> showSome() {

        Page<Player> all = playerDao.findAll(PageRequest.of(0, 10));
        return all.getContent();
    }

    @GetMapping("/showAny")
    public List<Player> showAny(@RequestParam Integer pageNum) {
        if (pageNum < 1) {
            throw new CetoException("查看页数不能小于1", CetoException.PLAYEREXC);
        }
        Page<Player> all = playerDao.findAll(PageRequest.of(pageNum - 1, 10));
        return all.getContent();
    }

    @Autowired
    private ThreadLocalRandom threadLocalRandom;

    @PostMapping("/insert")
    public Player insert(@RequestBody Player player) {
        player.setPlayerId(0);
        player.setVersion(0);

        player.setPlayerCode("811"+String.format("%04d", threadLocalRandom.nextInt(9999)));
        return playerDao.save(player);
    }

    @DeleteMapping("/delete/{code}")
    public Boolean delete(@PathVariable("code") String code) {

        try {
            playerDao.deleteByPlayerCode(code);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private QPlayer p = QPlayer.player;

    @PostMapping("/query")
    public PageResult<Player> query(
            @RequestBody PlayerSearchForm playerSearchForm) {
        Integer pageNum = playerSearchForm.getPageNum();
        Integer pageSize = playerSearchForm.getPageSize();
        if (pageNum < 1 || pageSize <= 0) {
            throw new CetoException("查询页数或数量不合法", CetoException.PLAYEREXC);
        }
        Integer pageStart = (pageNum - 1) * pageSize;
        PlayerQueryCondition qc = playerSearchForm.getQueryCondition();

        BooleanBuilder builder = new BooleanBuilder();
        /*
        *     private String nickNameSml;
    private Integer goldCoinMax;
    private Integer goldCoinMin;
    private List<Profession> professions;
        * */
        if (StringUtils.hasText(qc.getNickNameSml())) {

            builder.and(p.nickname.like("%" + qc.getNickNameSml() + "%"));
        }
        if (qc.getGoldCoinMax() != null && qc.getGoldCoinMax() > 0) {

            builder.and(p.goldCoin.loe(qc.getGoldCoinMax()));
        }
        if (qc.getGoldCoinMin() != null && qc.getGoldCoinMin() > 0) {

            builder.and(p.goldCoin.goe(qc.getGoldCoinMin()));
        }
        if (!CollectionUtils.isEmpty(qc.getProfessions())) {

            builder.and(p.profession.in(qc.getProfessions()));
        }


        QueryResults<Player> playerQueryResults = jpaQueryFactory.selectFrom(p)
                .where(builder)
                .orderBy(p.goldCoin.desc())
                .offset(pageStart)
                .limit(pageSize)
                .fetchResults();
        PageResult<Player> playerPageResult = new PageResult<>();
        playerPageResult.setResults(playerQueryResults.getResults());
        playerPageResult.setTotal(playerQueryResults.getTotal());
        return playerPageResult;
    }

    @GetMapping("/suggest")
    public List<Player> findSuggest(@RequestParam("nickname") String nickname) {
        return playerDao.findByNicknameLike("%" + nickname + "%");
    }

}
